<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="10">
        <el-card style="width: 100%">
          <div>
            <p style="text-align: center; color: grey">新增上报</p>
            <br />
            <el-form>
              <el-form-item label="管养单位" prop="unit">
                <el-input v-model="addForm.unit" placeholder="请输入管养单位"></el-input>
              </el-form-item>
              <el-form-item label="路线编号" prop="route">
                <el-input v-model="addForm.route" placeholder="请输入路线编号"></el-input>
              </el-form-item>
              <el-form-item label="图像名称" prop="imgname">
                <el-input
                  v-model="addForm.imgname"
                  placeholder="请输入图像名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="拍摄时间" prop="time">
                <el-date-picker
                  v-model="addForm.time"
                  type="date"
                  placeholder="选择日期时间"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="损坏类型" prop="damage">
                <el-input
                  v-model="addForm.damage"
                  placeholder="请输入损坏类型"
                ></el-input>
              </el-form-item>
              <el-form-item label="图片上传" prop="imgpath">
                <input type="file" @change="handleFileChange" accept="image/*" />
              </el-form-item>
              <el-form-item label="经度" prop="longitude">
                <el-input v-model="addForm.longitude" placeholder="请输入经度"></el-input>
              </el-form-item>
              <el-form-item label="纬度" prop="latitude">
                <el-input v-model="addForm.latitude" placeholder="请输入纬度"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="addProject">新增</el-button>
              </el-form-item>
              <el-divider></el-divider>
              <el-form-item label="批量上传">
                <div>
                  选择excel文件：
                  <input type="file" @change="handleExcelChange" accept=".xlsx, .xls" />
                </div>
                <br />
                <div>
                  上传图片：
                  <input
                    type="file"
                    accept="image/*"
                    multiple
                    @change="handlePicChange"
                  />
                </div>
                <br />
                <el-button type="primary" @click="uploadExcel">上传</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :span="14">
        <el-card>
          <el-table :data="projects" border style="width: 100%; height: 550px">
            <el-table-column prop="unit" label="管养单位"></el-table-column>
            <el-table-column prop="route" label="路线编号"></el-table-column>
            <el-table-column prop="imgname" label="图像名称"></el-table-column>
            <el-table-column prop="time" label="拍摄时间"></el-table-column>
            <el-table-column prop="damage" label="损坏类型"></el-table-column>
            <el-table-column prop="imgpath" label="图片">
              <template #default="{ row }">
                <img
                  :src="'http://localhost:3000/' + row.imgpath.substring(7)"
                  alt=""
                  style="width: 100px; height: 100px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isdispose" label="是否处置">
              <template #default="{ row }">
                <span>{{ row.isdispose ? "已处置" : "未处置" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="disposeNote" label="处置备注"></el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="text" @click="reback(row.id)">退回处置</el-button>
                <el-button type="text" @click="deleteProject(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import http from "../utils/http";
import * as XLSX from "xlsx";
const userId = localStorage.getItem("ms_id");
const excelFile = ref(null);
const picFiles = ref(null);

const reback = async (id) => {
  try {
    const response = await http.post("/project/revokeDeal", { id });
    if (response.data.code === 200) {
      ElMessage.success("项目状态更新成功");
      fetchProjects(); // 重新获取所有项目
    } else {
      ElMessage.error("项目状态更新失败");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("项目状态更新失败");
  }
};

const handleExcelChange = (event) => {
  excelFile.value = event.target.files[0];
};
const handlePicChange = (event) => {
  picFiles.value = event.target.files;
};

const uploadExcel = async () => {
  if (!excelFile.value || !picFiles.value) {
    ElMessage.error("请上传表格和图片");
    return;
  }
  console.log(excelFile.value, picFiles.value);
  //excel文件解析
  const reader = new FileReader();
  reader.onload = async (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const json = XLSX.utils.sheet_to_json(sheet);
    console.log(json);
    //     {
    //     "管养单位": "S21管理局",
    //     "路线编号": "S21",
    //     "图像名称": "标线损坏1.jpg",
    //     "经度": 87.53,
    //     "纬度": 46.59,
    //     "拍摄时间": 44927,
    //     "损坏类型": "标线缺失"
    // }
    //修改json的key
    json.forEach((item) => {
      item.unit = item["管养单位"];
      item.route = item["路线编号"];
      item.imgname = item["图像名称"];
      item.longitude = item["经度"];
      item.latitude = item["纬度"];
      //44927转换为日期
      item.time = item["拍摄时间"];
      item.time = new Date((item.time - 25569) * 86400 * 1000);

      item.damage = item["损坏类型"];
      item.isdispose = false;
      item.gemo = {
        type: "Point",
        coordinates: [item.longitude, item.latitude],
      };
      item.userId = userId;
      item.imgpath = "";
      delete item["管养单位"];
      delete item["路线编号"];
      delete item["图像名称"];
      delete item["经度"];
      delete item["纬度"];
      delete item["拍摄时间"];
      delete item["损坏类型"];
    });
    //上传图片
    for (let i in json) {
      await new Promise((resolve, reject) => {
        //选择对应名称的图片file
        const file = Array.from(picFiles.value).find(
          (item) => item.name === json[i].imgname
        );
        if (!file) {
          ElMessage.error(json[i].imgname + "图片不存在");
          reject();
        }
        const formData = new FormData();
        formData.append("file", file);
        http
          .post("/upload", formData)
          .then((res) => {
            if (res.data.code === 200) {
              json[i].imgpath = res.data.data.path;
              resolve();
            } else {
              ElMessage.error("图片上传失败");
              reject();
            }
          })
          .catch((error) => {
            console.error(error);
            ElMessage.error("图片上传失败");
            reject();
          });
      });
    }
    //上传数据
    try {
      const response = await http.post("/project/addBatch", { projects: json });
      if (response.data.code === 200) {
        ElMessage.success("项目批量添加成功");
        fetchProjects(); // 重新获取所有项目
      } else {
        ElMessage.error("项目批量添加失败");
      }
    } catch (error) {
      console.error(error);
      ElMessage.error("项目批量添加失败");
    }
  };
  reader.readAsArrayBuffer(excelFile.value);
};
const projects = ref([]);
const addForm = reactive({
  unit: "",
  route: "",
  imgname: "",
  longitude: "",
  latitude: "",
  time: "",
  damage: "",
  imgpath: "",
});

const fetchProjects = async () => {
  try {
    const response = await http.get("/project/all");
    projects.value = response.data.data;
  } catch (error) {
    console.error(error);
  }
};

const addProject = async () => {
  try {
    const postdata = {
      unit: addForm.unit,
      route: addForm.route,
      imgname: addForm.imgname,
      longitude: addForm.longitude,
      latitude: addForm.latitude,
      time: addForm.time,
      damage: addForm.damage,
      imgpath: addForm.imgpath,
      isdispose: false,
      gemo: {
        type: "Point",
        coordinates: [addForm.longitude, addForm.latitude],
      },
      userId,
    };

    const response = await http.post("/project/add", postdata);
    if (response.data.code === 200) {
      ElMessage.success("项目添加成功");
      fetchProjects(); // 重新获取所有项目
    } else {
      ElMessage.error("项目添加失败");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("项目添加失败");
  }
};

const deleteProject = async (id) => {
  try {
    const response = await http.post("/project/delete", { id });
    if (response.data.code === 200) {
      ElMessage.success("项目删除成功");
      fetchProjects(); // 重新获取所有项目
    } else {
      ElMessage.error("项目删除失败");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("项目删除失败");
  }
};

const updateDeal = async (id) => {
  try {
    const response = await http.post("/project/updateDeal", { id });
    if (response.data.code === 200) {
      ElMessage.success("项目状态更新成功");
      fetchProjects(); // 重新获取所有项目
    } else {
      ElMessage.error("项目状态更新失败");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("项目状态更新失败");
  }
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (!file) {
    return;
  }
  const formData = new FormData();
  formData.append("file", file);
  http
    .post("/upload", formData)
    .then((res) => {
      if (res.data.code === 200) {
        addForm.imgpath = res.data.data.path;
        ElMessage.success("图片上传成功");
      } else {
        ElMessage.error("图片上传失败");
      }
    })
    .catch((error) => {
      console.error(error);
      ElMessage.error("图片上传失败");
    });
};

fetchProjects();
</script>
